// 封装登录框逻辑
import { App, createApp, onUnmounted } from "vue";
import loginDialog from "./loginDialog.vue";

let dialogInstance: App | null = null         // 挂载
let dialogElement: HTMLElement | null = null  // dom

const loginDialogPlugin  = {
  install: (app: App) => {
    app.config.globalProperties.$showLoginDialog = () => {
      if (!dialogInstance) {
        // 创建vue的实例对象
        dialogInstance = createApp(loginDialog)
        // 挂载到dom中
        dialogElement = document.createElement('div')
        document.body.appendChild(dialogElement)
        dialogInstance.mount(dialogElement)
      }
      onUnmounted(() => {
        if (dialogInstance && dialogElement) {
          dialogInstance.unmount()
          document.body.removeChild(dialogElement)
          dialogInstance = null
          dialogElement = null
        }
      })
    }
    app.config.globalProperties.$hideLoginDialog = () => {
      if (dialogInstance && dialogElement) {
        dialogInstance.unmount()
        document.body.removeChild(dialogElement)
        dialogInstance = null
        dialogElement = null
      }
    }
  }
}
export default loginDialogPlugin